<template>
  <el-drawer
    :visible.sync="dialogVisible"
    :before-close="handleClose"
    :with-header="false"
    :class="{'order-setting-drawer': !showMobilePage, 'mobile-drawer': showMobilePage}">
    <div class="order-setting-main">
      <div class="title-container">
        <Title title="请筛选您要展示的账号指标">
          <div class="title-tip">（选中的指标将被展示于账号列表中）</div>
        </Title>
        <div>
          <el-select
            v-model="curView"
            :filter-method="getViewList"
            filterable
            size="small"
            value-key="id"
            clearable
            placeholder="请选择视图"
            @visible-change="(val) => {if(val) getViewList()}"
          >
            <el-option label="默认视图" value=""/>
            <el-option
              v-for="item in allViewData"
              :key="item.id"
              :label="item.name"
              :title="item.name"
              :value="item"
            />
          </el-select>
          <el-button v-if="!curView" class="default-btn" size="small" type="info" @click="showViewListDialog(false)">新建视图</el-button>
        </div>
      </div>
      <div :style="{maxHeight: maxHeight}" class="draggable-container">
        <div class="left">
          <template v-for="tableItem in tableList">
            <div v-if="tableItem.children.length" :key="tableItem.fieldName" class="draggable-list">
              <div class="title">
                <div class="title-dot"/>
                <div class="title-text">{{ tableItem.name }}</div>
                <el-checkbox
                  :indeterminate="getSelectShowNum(tableItem.children) > 0 && getSelectShowNum(tableItem.children) < tableItem.children.length"
                  :value="getSelectShowNum(tableItem.children) === tableItem.children.length"
                  style="margin-left:10px;"
                  @change="handleCheckAllChange(tableItem)">全选</el-checkbox>
              </div>
              <draggable
                v-model="tableItem.children"
                v-bind="{
                  group: tableItem.fieldName,
                  animation: 200,
                  ghostClass: 'ghost'
                }"
                :disabled="true"
                :move="checkMove"
                handle=".draggable-move"
                filter=".undrag">
                <transition-group type="transition" class="draggable-item-list">
                  <template v-for="(item) in tableItem.children" >
                    <div
                      v-if="getPropsData(item) || item.isDynamicKey"
                      :key="item.fieldName"
                      :class="{'mobile-item':showMobilePage, 'undrag': getPropsData(item).disabledMove}"
                      class="draggable-item">
                      <div class="check">
                        <el-checkbox :disabled="getPropsData(item).disableShow" v-model="item.isShow" @change="checkChangeSort"/>
                      </div>
                      <div
                        :class="{'activetext': item.isShow}"
                        class="draggable one-row">
                        <ToolTip :content="getPropsData(item).label || item.name" />
                        <span v-if="getPropsData(item).disableShow" class="draggable-tag">*</span>
                      </div>
                    </div>
                  </template>
                </transition-group>
              </draggable>
            </div>
          </template>
        </div>
        <div class="right">
          <div class="title">
            <div class="title-dot"/>
            <div class="title-text">字段排序<span class="tip">{{ orderTip }}</span></div>
          </div>
          <draggable
            v-model="sortList"
            v-bind="{
              animation: 200,
              ghostClass: 'ghost'
            }"
            :disabled="!viewData"
            :move="sortMove"
            handle=".draggable-move"
            filter=".undrag">
            <transition-group type="transition" class="draggable-item-list">
              <template v-for="(item) in sortList" >
                <div
                  v-if="getPropsData(item) || item.isDynamicKey"
                  :key="item.fieldName"
                  :class="{'mobile-item':showMobilePage, 'undrag': getPropsData(item).disabledMove || !viewData}"
                  class="draggable-item">
                  <div
                    :class="{'activetext': item.isShow, 'draggable-move': !getPropsData(item).disabledMove && !!viewData}"
                    class="draggable one-row">
                    <ToolTip :content="getPropsData(item).label || item.name" />
                    <span v-if="getPropsData(item).disableShow" class="draggable-tag">*</span>
                  </div>
                  <img v-if="!getPropsData(item).disabledMove && !!viewData" :src="draggableImg" class="draggable-img draggable-move" alt="" >
                </div>
              </template>
            </transition-group>
          </draggable>
        </div>
      </div>
    </div>
    <div v-loading="addLoading" class="order-setting-btn-container">
      <el-button type="primary" size="small" style="padding: 0 12px" @click="handelSubmit(false)">保存并关闭</el-button>
      <el-button v-if="!!curView" class="default-btn" size="small" type="info" @click="showViewListDialog(true)">保存视图</el-button>
      <el-button class="cancel-btn-style" size="small" type="info" @click="handleClose">取消</el-button>
      <img :src="resetFilterIcon" class="reset-btn" width="18" height="18" alt="" title="恢复默认" @click="handleDefault">
    </div>
    <ViewListDialog
      ref="viewListDialogRef"
      :platform="platform"
      :cur-view="curView"
      :table-list="tableList"
      :sort-list="sortList"
      style="margin: 0 12px"
      @changeView="changeView"
      @freshData="freshViewList"
      @resetList="resetList" />
  </el-drawer>
</template>
<script>
import Title from '@/components/Title';
import { tableFieldProps, initTableList } from '../mixins/listSettingData.js';
import { handelListSetting } from './utils';
import { editOrderSetting } from '@/api/order';
import { getViewList } from '@/api/resource';
import draggable from 'vuedraggable';
import draggableImg from '@/assets/orderlist/draggable.png';
import resetFilterIcon from '@/assets/setting/resetFilter.png';
import ElMessage from '@/utils/message';
import ViewListDialog from './ViewListDialog';
import { mapState } from 'vuex';
export default {
  name: 'OrderSetting',
  components: { Title, draggable, ViewListDialog },
  props: {
    platform: {
      type: String | Number,
      default: ''
    },
    dynamicKeyList: { // 自定义字段
      type: Object,
      default: () => {
        return {};
      }
    },
    viewData: {
      type: Object | String,
      default: () => {
        return '';
      }
    }
  },
  data() {
    return {
      draggableImg,
      resetFilterIcon,
      propsData: tableFieldProps,
      must: true,
      dialogVisible: false,
      addLoading: false,
      tableList: [],
      defalutList: [],
      maxHeight: '',
      allTableList: {},
      allViewData: {},
      sortList: []
    };
  },
  computed: {
    ...mapState({
      'showMobilePage': state => state.app.showMobilePage
    }),
    computedTableList: {
      get() {
        if (this.tableList && this.tableList.length) return this.tableList;
        return handelListSetting(this.handelData(initTableList), this.dynamicKeyList);
      },
      set(val) {
        this.tableList = val;
      }
    },
    curView: {
      get() {
        return this.viewData;
      },
      set(value) {
        const platform = this.platform || 'all';
        let listSetting = this.allTableList[platform] || [];
        if (value && value.data) {
          const data = this.jsonParse(value.data, null);
          if (data) listSetting = data;
        }
        this.tableList = this.handelData(listSetting);
        this.$emit('changeView', value);
        this.$nextTick(() => {
          this.initSortList(this.tableList, value);
        });
      }
    },
    orderTip() {
      return !this.viewData ? '默认视图不支持排序功能，自定义列表顺序请新建视图' : '列表字段的排序将按此处配置从左到右，从上到下依次排序';
    }
  },
  methods: {
    freshViewList() {
      this.getViewList('', true);
      this.$emit('freshViewList');
    },
    resetList() {
      this.$emit('resetList');
    },
    handelSubmit() {
      if (this.curView) {
        this.showViewListDialog(true, true);
        this.handleClose();
      } else {
        this.toSubmit();
      }
    },
    changeView(value) {
      this.$emit('changeView', value);
    },
    toSubmit(reset = false) {
      const platform = this.platform || 'all';
      const allTableList = this.allTableList;
      allTableList[platform] = '';
      const data = {
        list: '',
        type: 'resource'
      };
      if (this.tableList && this.tableList.length && !reset) {
        allTableList[platform] = this.tableList;
      }
      if (!allTableList[platform]) delete allTableList[platform];
      data.list = JSON.stringify(allTableList);
      this.addLoading = true;
      const loclView = this.getLocalView();
      editOrderSetting(data).then((res) => {
        this.addLoading = false;
        if (res.code) {
          if (loclView && loclView[platform]) {
            delete loclView[platform];
            localStorage.setItem('curView', JSON.stringify(loclView));
          }
          ElMessage.success('保存成功');
          this.$emit('handelSubmit');
          this.handleClose();
        } else {
          this.$message.error(res.message);
        }
      }).catch((err) => {
        this.addLoading = false;
        console.log(err);
      });
    },
    initSortList(list = this.tableList || [], viewData) {
      const curView = viewData || this.viewData;
      let ans = [];
      list.forEach(i => {
        ans = ans.concat(i.children);
      });
      if (curView && curView.data && !Array.isArray(curView.data)) {
        const tableAns = _.cloneDeep(ans);
        const { sortList } = this.jsonParse(curView.data) || {};
        ans = [];
        sortList.forEach(i => {
          const findItem = tableAns.find(j => j.fieldName === i.fieldName);
          if (findItem) {
            ans.push(findItem);
          }
        });
        this.sortList = ans.filter(el => !!el.isShow);
      } else {
        this.sortList = this.getSortList();
      }
      this.sortList = ans.filter(el => !!el.isShow);
    },
    getSortList(list = this.tableList || []) {
      let ans = [];
      list.forEach(i => {
        ans = ans.concat(i.children);
      });
      return ans.filter(el => !!el.isShow);
    },
    checkChangeSort() {
      let ans = [];
      this.tableList.forEach(i => {
        ans = ans.concat(i.children);
      });
      ans = ans.filter(el => !!el.isShow);
      ans.forEach(k => {
        if (!this.sortList.find(i => i.fieldName === k.fieldName)) { this.sortList.push(k); }
      });
      const newSortArr = [];
      this.sortList.forEach(e => {
        const findIndex = ans.findIndex(i => i.fieldName === e.fieldName);
        if (findIndex !== -1) {
          newSortArr.push(e);
        }
      });
      this.sortList = newSortArr;
    },
    getPropsData(item) {
      const propsData = this.propsData;
      return propsData[item.fieldName] || {};
    },
    openDialog(allTableList, allViewData) {
      allTableList = _.cloneDeep(allTableList);
      this.allViewData = _.cloneDeep(allViewData);

      const clientHeight = window.innerHeight;
      this.maxHeight = (clientHeight - 120) + 'px';

      const platform = this.platform || 'all';
      let listSetting = allTableList[platform] || [];
      if (this.curView && this.curView.data) {
        const data = this.jsonParse(this.curView.data, null);
        if (data) listSetting = data;
      }
      this.tableList = this.handelData(listSetting);
      this.initSortList();
      this.allTableList = allTableList;
      this.dialogVisible = true;
    },
    // 原自账号信息改为固定
    removeItem() {
      const fields = [{ parentKey: 'accountInfo', childKey: 'accountAllField' }];
      fields.forEach(field => {
        const parentItem = this.tableList.find(j => j.fieldName === field.parentKey);
        if (parentItem && parentItem.children && parentItem.children.length) {
          const index = parentItem.children.findIndex(k => k.fieldName === field.childKey);
          parentItem.children.splice(index, 1);
        }
      });
    },
    handleClose() {
      this.dialogVisible = false;
    },
    handelData(data) {
      const list = Array.isArray(data) ? data : data.tableList || [];
      const dataList = _.cloneDeep(list);
      const platform = Number(this.platform);
      dataList.forEach(i => {
        if (platform) {
          i.children = i.children.filter(j => {
            const props = this.getPropsData(j);
            return !props.platform || props.platform.length === 0 || props.platform.includes(platform);
          });
        }
      });
      return dataList;
    },
    checkMove(evt) {
      const dataProp = this.getPropsData(evt.relatedContext.element);
      return !dataProp.disabledMove;
    },
    sortMove(evt) {
      return true;
    },
    showViewListDialog(isSave = false, resetList = false) {
      this.$refs['viewListDialogRef'].operateView(isSave, resetList);
    },
    handleDefault() {
      // this.tableList = handelListSetting(this.handelData(initTableList), this.dynamicKeyList);
      this.toSubmit(true);
    },
    handleCheckAllChange(item) {
      const showNum = this.getSelectShowNum(item.children);
      if (showNum >= item.children.length) {
        item.children.forEach(i => {
          if (!this.getPropsData(i).disableShow) {
            i.isShow = false;
          }
        });
      } else {
        item.children.forEach(i => {
          if (!this.getPropsData(i).disableShow) {
            i.isShow = true;
          }
        });
      }
      this.checkChangeSort();
    },
    getSelectShowNum(arr) {
      if (!arr || arr.length === 0) return 0;
      return arr.reduce((pre, cur) => {
        if (cur.isShow) pre++;
        return pre;
      }, 0);
    },
    /**
     * 视图
     */
    jsonParse(str, defaultVal = {}) {
      if (typeof str !== 'string') return str;
      try {
        return JSON.parse(str);
      } catch (error) {
        return defaultVal;
      }
    },
    getLocalView() {
      const loclView = localStorage.getItem('curView') || '{}';
      return this.jsonParse(loclView);
    },
    async getViewList(name, changeView) {
      try {
        const platform = this.platform || 'all';
        const data = {
          page: 1,
          perPage: 30,
          name: name || '',
          platform
        };
        const res = await getViewList(data);
        if (res.code === 200 && res.data.items) {
          this.allViewData = res.data.items;
        }
        if (changeView && this.curView.id) {
          this.$emit('changeView', this.allViewData.find(j => j.id === this.curView.id));
        }
      } catch (error) {
        console.log(error);
      }
    }
  }
};
</script>
<style lang="scss" scoped>
.order-setting-drawer {
  & ::v-deep {
    .el-drawer {
      width: 1000px !important;
    }
  }
  .default-btn {
    padding: 0;
    width: 80px;
    height: 32px;
    border: 1px solid #406eff;
    border-radius: 4px;
    font-size: 14px;
    text-align: center;
    color: #406eff;
    margin-left: 12px;
  }
}
.draggable-list {
  margin-bottom: 32px;
}
.mobile-drawer {
    & ::v-deep {
    .el-drawer {
      width: 100% !important;
    }
  }
}
.order-setting-btn-container {
  display: flex;
  padding: 24px 24px 0 24px;
  .cancel-btn-style {
    width: 80px;
    height: 32px;
    padding: 0;
  }
  .reset-btn {
    cursor: pointer;
    margin: 7px 0 0 12px;
  }
}
.title-container {
  display: flex;
  height: 45px;
  padding: 0 24px 0 16px;
  align-items: center;
  border-bottom: 1px solid #F5F5F5;
}
.title-tip {
  font-size: 14px;
  color: #666;
}
.title {
  display: flex;
  align-items: center;
  margin-bottom: 10px;
  .title-dot {
    width: 4px;
    height: 4px;
    background: #406eff;
    margin-right: 6px;
  }
  .title-text {
    display: flex;
    align-items: center;
    font-size: 16px;
    color: #333;
    font-weight: bold;
    .tip {
      font-size: 14px;
      color: #999;
      margin-left: 4px;
    }
  }
}
.draggable-container {
  padding: 18px 24px 0 24px;
  @include scrollBar($x: hidden, $y: auto, $width: 12px);
  display: flex;
  justify-content: space-between;
  .left, .right {
    width: 50%;
    height: 100%;
  }
  .left {
    padding-right: 18px;
    border-right: 1px #F5F5F5 solid;
  }
  .right {
    padding-left: 18px;
  }
}
.draggable-item-list {
  display: flex;
  flex-wrap: wrap;
  border-top: 1px solid #EBEEFD;
  border-left: 1px solid #EBEEFD;
}
.one-row {
  display: flex;
  overflow: hidden;
  align-items: center;
}
.mobile-item {
  width: 50% !important;
}
.draggable-item {
  position: relative;
  display: flex;
  align-items: center;
  border-bottom: 1px solid #EBEEFD;
  border-right: 1px solid #EBEEFD;
  // width: 160px;
  width: 33.3%;
  height: 47px;
  padding: 0 12px;
  background-color: #fff;
  overflow: hidden;
  .check {
    margin-right: 8px;
  }
  .draggable {
    flex: 1;
    font-size:14px;
    font-family:PingFangSC-Regular,PingFang SC;
    color:rgba(20,28,61,1);
    line-height:1.2;
  }
  .draggable-img {
    width: 16px;
    height: 16px;
    visibility: hidden;
    position: absolute;
    right: 6px;
    top: 15px;
  }
  &:hover {
    background-color: #FAFAFA;
    .draggable-img {
      visibility: visible;
    }
  }
  .draggable-move {
    cursor: move;
  }
  .draggable-tag {
    color: #FF4E5F;
    font-size: 12px;
    margin-left: 3px;
  }
}

.activetext{
  font-weight: bold;
}
</style>
